# __author__ = "James Zhang"
# !/usr/bin/python
# -*- coding: utf-8 -*-
import six
import json
from functools import WRAPPER_ASSIGNMENTS, update_wrapper, wraps

from core.utils.encoders import JSONEncoder


def available_attrs(fn):
    if six.PY3:
        return WRAPPER_ASSIGNMENTS
    else:
        return tuple(a for a in WRAPPER_ASSIGNMENTS if hasattr(fn, a))


def method_decorator(decorator):
    def _dec(func):
        def _wrapper(self, *args, **kwargs):
            @decorator
            def bound_func(*args2, **kwargs2):
                return func.__get__(self, type(self))(*args2, **kwargs2)
            return bound_func(*args, **kwargs)

        @decorator
        def dummy(*args, **kwargs):
            pass
        update_wrapper(_wrapper, dummy)

        update_wrapper(_wrapper, func)

        return _wrapper

    update_wrapper(_dec, decorator, assigned=available_attrs(decorator))

    if hasattr(decorator, "__name__"):
        _dec.__name__ = "method_decorator(%s)" % decorator.__name__
    else:
        _dec.__name__ = "method_decorator(%s" % decorator.__class__.__name__

    return _dec


def JSON2Response(func):
    @wraps(func)
    def wrapped(self, data, *args, **kwargs):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header("Access-Control-Allow-Credentials", 'true')
        self.set_header('Content-Type', 'application/json')
        json_data = json.dumps(data, cls=JSONEncoder)
        func(self, json_data, *args, **kwargs)
    return wrapped
